<template>
  <!-- 
    1.使用树状表格 :isTreeTable="true"   默认false
    2.表格控制按钮 :showTableControl="true", 默认 false
    3.显示分页  :ispagination="false"   默认为true
    4.是否开启表格复选框，:showcheckbox="true" 默认false
    5.表头headData不可包含 show 属性，此字段已被本组件占用，用于控制单元格显示
    6.表格数据和表头的对齐方式默认left, 若更改请传值，如：:align="'center'",
        若需更改某一列的对齐方式，在表头数据添加align属性 如:
        headData:[
            {
                prop:'id',
                align:'center'
            }
        ]
 -->
  <div id="tableVue">
    <div class="controlBtn" v-if="showTableControl">
      <div class="topLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addNew"
          size="mini"
          >新增</el-button
        >
        <el-button
          type="success"
          icon="el-icon-edit"
          :disabled="!ableEditCopy"
          @click="edit"
          size="mini"
          >修改</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="!ableDelCopy"
          @click="deltable"
          size="mini"
          >删除</el-button
        >
        <el-button
          type="warning"
          @click="exportExcel"
          icon="el-icon-download"
          size="mini"
          >导出</el-button
        >
      </div>
      <div class="topRight">
        <el-button-group>
          <el-button icon="el-icon-search" size="mini"></el-button>
          <el-button
            icon="el-icon-refresh"
            @click="refreshData"
            size="mini"
          ></el-button>
          <el-popover placement="top-start" width="150" trigger="click">
            <el-button
              icon="el-icon-s-grid"
              slot="reference"
              size="mini"
            ></el-button>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAllhead"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <el-checkbox-group
              v-model="checkedHeads"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="item in allHead"
                :label="item"
                v-model="itemIscheck"
                :key="item"
                >{{ item }}</el-checkbox
              >
            </el-checkbox-group>
          </el-popover>
        </el-button-group>
      </div>
    </div>
    <el-table
      v-loading="loading"
      @selection-change="tabselect"
      :data="tableData"
      :border="border"
      :height="height"
      :stripe="stripe"
      style="width: 100%"
      :tree-props="
        isTreeTable ? { children: 'children', hasChildren: 'hasChildren' } : ''
      "
      :row-key="isTreeTable ? 'id' : ''"
    >
      <el-table-column
        v-if="showcheckbox"
        type="selection"
        align="center"
        width="55"
      >
      </el-table-column>
      <el-table-column
        :align="item.align || align"
        v-if="item.show"
        v-for="(item, index) in headDataCopy"
        :prop="item.prop"
        :label="item.label"
        :key="index"
        :width="item.width"
      >
        <template slot-scope="{ $index, row }">
          <div v-if="!item.slot">
            {{ row[item.prop] | clearEmptyObj }}
          </div>
          <div v-if="item.slot">
            <slot :name="item.prop" v-bind:row="row"></slot>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        v-if="isoperation"
        width="150px"
        align="center"
        label="操作"
      >
        <template slot-scope="{ row, $index }">
          <slot name="operation" :row="{ item: row, index: $index }"></slot>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        class="pagination"
        v-if="ispagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentpage + 1"
        :page-sizes="pagesizes"
        :page-size="pagesize"
        layout="total,prev, pager, next, sizes"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { formatTime } from "@/config/isTimetamp";
import * as XLSX from "xlsx";
export default {
  name: "eveningStar",
  data() {
    return {
      loading: true, //加载动画
      ableDelCopy: this.ableDel,
      ableEditCopy: this.ableEdit,
      headDataCopy: this.headData,
      checkedHeads: [], //表头显示项
      allHead: [], //所有表头复选框组
    };
  },
  watch: {
    checkedHeads: {
      immediate: true,
      handler(newVal) {
        this.headDataCopy.forEach((obj) => {
          newVal.some((item) => item == obj.label)
            ? this.$set(obj, "show", true)
            : this.$set(obj, "show", false);
        });
      },
    },
    ableDel(newtype) {
      this.ableDelCopy = newtype;
    },
    ableEdit(newtype) {
      this.ableEditCopy = newtype;
    },
  },
  filters: {
    clearEmptyObj(val) {
      let isTime = /^\d{10,13}$/;
      if (typeof val == "object" && Object.keys(val).length == 0) {
        return "";
      } else if (isTime.test(val)) {
        return formatTime(val);
      } else {
        return val;
      }
    },
  },
  props: {
    // 是否开启树状表格
    isTreeTable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 是否显示表格新增、导出等控制按钮
    showTableControl: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 多选是否可编辑
    ableEdit: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 多选是否可删除
    ableDel: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 右上角全选的未全选状态
    isIndeterminate: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 右上复选框组中每项的选中状态
    itemIscheck: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 右上表头控制的全选复选框
    checkAllhead: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 是否启用表格复选框
    showcheckbox: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 表格数据的名字
    tableData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 数据对齐方式
    align: {
      type: String,
      default: () => {
        return "left";
      },
    },
    // 表头的数据
    headData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 是否展示操作
    isoperation: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 是否展示分页
    ispagination: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 是否斑马纹
    stripe: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    // 是否边框
    border: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 固定表格头部
    height: {
      type: String,
      default: () => {
        return "fit-content";
      },
    },
    // 当前第几页
    currentpage: {
      type: Number,
      default: () => {
        return 1;
      },
    },
    // 切换一页多少条数据的选项
    pagesizes: {
      type: Array,
      default: () => {
        return [10, 20, 30, 40, 50];
      },
    },
    // 一页几条
    pagesize: {
      type: Number,
      default: () => {
        return 10;
      },
    },
    // 总条数
    total: {
      type: Number,
      default: () => {
        return 0;
      },
    },
  },
  methods: {
    // 表头是否全部显示
    handleCheckAllChange(val) {
      this.checkedHeads = this.allHead;
      this.isIndeterminate = false;
      this.checkAllhead = true;
    },
    // 设置表头显示项
    handleCheckedCitiesChange(value) {
      if (value.length == 1) {
        this.lastitem = value[0];
      }
      if (value.length == 0) {
        this.$notify({
          title: "请至少选择一列",
          type: "warning",
        });
        this.checkedHeads.push(this.lastitem);
      }
      this.isIndeterminate = value.length != this.allHead.length;
      this.checkAllhead = value.length === this.allHead.length;
      value.length > 0 && value.length < this.allHead.length;
    },

    // 组件通信
    // 表格复选框事件
    tabselect(selection) {
      this.$emit("tabselect", selection);
    },
    // 新增
    addNew() {
      this.$emit("addNew");
      this.$bus.$emit("getPicChoose");
    },
    // 编辑
    edit() {
      this.$emit("edit");
    },
    // 删除
    deltable() {
      this.$emit("deltable");
    },
    // 导出
    exportExcel() {
      const sheet = XLSX.utils.json_to_sheet(this.tableData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, sheet, "Sheet1");
      XLSX.writeFile(workbook, "table.xlsx");
    },
    // 刷新
    refreshData() {
      this.$emit("refreshData");
    },
    handleSizeChange(val) {
      let _self = this;
      _self.$emit("SizeChange", val);
    },
    handleCurrentChange(val) {
      let _self = this;
      _self.$emit("CurrentChange", val);
    },
  },
  mounted() {
    setTimeout(() => {
      this.loading = false;
    }, 450);
    this.headData.forEach((item) => {
      if (item.hasOwnProperty("label")) {
        this.allHead.push(item.label);
        this.checkedHeads.push(item.label);
      }
    });
  },
};
</script>
<style lang="less">
#tableVue {
  .el-button + .el-button {
    margin-left: 0 !important;
  }
  .controlBtn {
    width: 100%;
    display: flex;
    margin: 10px;
    align-items: center;
    justify-content: space-between;
    .topRight {
      margin-right: 12px;
    }
  }
  .el-table .cell {
    font-weight: bold !important;
    font-size: 12px !important;
  }
  .el-table__body .cell > div {
    font-weight: normal !important;
    padding-right: 12px;
    padding-left: 0;
    display: inline-block;
  }
  .el-table .cell:first-child {
    padding: 0 !important;
  }
  .el-table .el-table__cell {
    padding: 0;
  }
  .el-table__row td {
    height: 62px !important;
  }
  .el-table__body-wrapper {
    // min-height: 62px!important;
    overflow-y: scroll;
    max-height: 500px !important;
    height: fit-content !important;
  }
  .pagination {
    margin-top: 8px;
  }
  .el-button--warning {
    color: #fff;
    background-color: #ffba00;
    border-color: #ffba00;
    &:hover {
      background-color: #ffba00cc;
      border-color: #ffba00cc;
    }
  }
}
</style>